package cn.iocoder.yudao.module.trade.service.order.handler;

import cn.hutool.core.lang.Assert;
import cn.iocoder.yudao.module.agent.dal.dataobject.brokerageuser.AgentBrokerageUserDO;
import cn.iocoder.yudao.module.agent.enums.AgentBrokerageRecordBizTypeEnum;
import cn.iocoder.yudao.module.agent.service.bo.borkeragerecord.BorkerageRecordAddReqBO;
import cn.iocoder.yudao.module.agent.service.brokeragerecord.AgentBrokerageRecordService;
import cn.iocoder.yudao.module.agent.service.brokerageuser.AgentBrokerageUserService;
import cn.iocoder.yudao.module.member.api.user.MemberUserApi;
import cn.iocoder.yudao.module.member.api.user.dto.MemberUserRespDTO;
import cn.iocoder.yudao.module.product.api.sku.ProductSkuApi;
import cn.iocoder.yudao.module.product.api.spu.ProductSpuApi;
import cn.iocoder.yudao.module.trade.convert.order.TradeOrderConvert;
import cn.iocoder.yudao.module.trade.dal.dataobject.order.TradeOrderDO;
import cn.iocoder.yudao.module.trade.dal.dataobject.order.TradeOrderItemDO;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;

@Component
public class TradeAgentOrderHandler implements TradeOrderHandler{

    @Resource
    private MemberUserApi memberUserApi;
    @Resource
    private ProductSpuApi productSpuApi;

    @Resource
    private ProductSkuApi productSkuApi;

    @Resource
    private AgentBrokerageRecordService agentBrokerageRecordService;

    @Resource
    private AgentBrokerageUserService agentBrokerageUserService;

    @Override
    public void afterPayOrder(TradeOrderDO order, List<TradeOrderItemDO> orderItems) {
        if(!agentBrokerageUserService.hasBinded(order.getUserId())){
            return;
        }
        addBrokerage(order.getUserId(), orderItems);
    }

    /**
     * 创建分销记录
     * <p>
     * 目前是支付成功后，就会创建分销记录。
     * <p>
     * 业内还有两种做法，可以根据自己的业务调整：
     * 1. 确认收货后，才创建分销记录
     * 2. 支付 or 下单成功时，创建分销记录（冻结），确认收货解冻或者 n 天后解冻
     *
     * @param userId  用户编号
     * @param orderItems 订单项
     */
    protected void addBrokerage(Long userId, List<TradeOrderItemDO> orderItems) {
        MemberUserRespDTO user = memberUserApi.getUser(userId);
        Assert.notNull(user);

        // 每一个订单项，都会去生成分销记录
        List<BorkerageRecordAddReqBO> addList = convertList(orderItems, item -> TradeOrderConvert.INSTANCE.convertAgentRecord(user, item));
        agentBrokerageRecordService.addBrokerage(userId, AgentBrokerageRecordBizTypeEnum.ORDER, addList);

        int totalPrice = 0;
        for (BorkerageRecordAddReqBO item : addList){
            totalPrice += item.getPayPrice();
        }
        agentBrokerageUserService.updateOrderCount(userId, addList.size(), totalPrice);
    }

    @Override
    public void afterCancelOrderItem(TradeOrderDO order, TradeOrderItemDO orderItem) {
        if(!agentBrokerageUserService.hasBinded(order.getUserId())){
            return;
        }

        AgentBrokerageUserDO brokerageUserDO = agentBrokerageUserService.getBrokerageUserByUserId(order.getUserId());

        agentBrokerageRecordService.cancelBrokerage(brokerageUserDO.getAgentUserId(), brokerageUserDO.getUserId(), orderItem.getId());

        agentBrokerageUserService.updateOrderCount(brokerageUserDO.getUserId(), -1, -orderItem.getPayPrice());
    }
}
